package config

import (
	"context"
	"fmt"
	"log"
	"smartposts/internal/global"
	"smartposts/internal/models"
	"smartposts/internal/utils"
	"github.com/redis/go-redis/v9"
)

func InitRedis() {
	ctx := context.Background()

	addr := fmt.Sprintf("%s:%d", AppConfig.Redis.Host, AppConfig.Redis.Port)
	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: "",
		DB:       AppConfig.Redis.DB,
	})

	if _, err := client.Ping(ctx).Result(); err != nil {
		log.Fatalf("failed to connect Redis, got error: %v", err)
	}

	global.RedisDB = client

	if err := warmUpHotPostsCache(); err != nil {
		log.Printf("failed to warm up hot posts cache: %v", err)
	}
}

func warmUpHotPostsCache() error {
	ctx := context.Background()
	var posts []models.Post
	if err := global.Db.Find(&posts).Error; err != nil {
		return fmt.Errorf("failed to get posts from db: %w", err)
	}

	if len(posts) == 0 {
		log.Println("No posts found to warm up cache.")
		return nil
	}

	members := make([]redis.Z, len(posts))
	for i, post := range posts {
		members[i] = redis.Z{
			Score: utils.CompositeScore(post),
			Member: post.ID,
		}
	}

	if err := global.RedisDB.ZAdd(ctx, "hot_posts", members...).Err(); err != nil {
		return fmt.Errorf("failed to add posts to hot_posts sorted set: %w", err)
	}

	log.Printf("Successfully warmed up hot posts cache with %d posts.", len(posts))
	return nil
}
